import OSS, { MultipartUploadResult, Options, PutObjectResult } from 'ali-oss';
import { uuid } from './uuid';
export class OssUploadApi {
  static ossClient: OSS | null;
  // eslint-disable-next-line no-use-before-define
  static OssUploadApiInstance: OssUploadApi | null;

  static getOssUploadApiInstance(ossConfigParam?: Partial<Options>) {
    const ossConfig = {
      region: 'oss-cn-hangzhou',
      accessKeyId: 'o6jf22DofRcUAUgz',
      accessKeySecret: 'CQgxlwx1yJOnNOrTokcakAKdB27dSF',
      bucket: 'logibeat-test',
      ...ossConfigParam,
    };
    if (!OssUploadApi.OssUploadApiInstance) {
      OssUploadApi.OssUploadApiInstance = new OssUploadApi();
      OssUploadApi.ossClient = new OSS(ossConfig);
    }
    return OssUploadApi.OssUploadApiInstance;
  }

  static deleteOssUploadApiInstance() {
    if (OssUploadApi.OssUploadApiInstance) {
      OssUploadApi.OssUploadApiInstance = null;
      OssUploadApi.ossClient = null;
    }
  }

  //参数1： 填写Object完整路径。Object完整路径中不能包含Bucket名称。（ 对象是OSS存储数据的基本单元，也被称为OSS的文件。和传统的文件系统不同，对象没有文件目录层级结构的关系。对象由元信息（Object Meta），用户数据（Data）和文件名（Key，参数1）组成）
  // 您可以通过自定义文件名（例如exampleobject.txt）或文件完整路径（例如exampledir/exampleobject.txt）的形式实现将数据上传到当前Bucket或Bucket中的指定目录。
  // data对象可以自定义为file对象、Blob数据或者OSS Buffer。
  getFilePath(file: File | Blob, path: string, phone: string) {
    let ext;
    const date = new Date();
    const YYYY = date.getFullYear() + '';
    const MM = `0${date.getMonth()}`.slice(-2);
    const DD = `0${date.getDate()}`.slice(-2);
    const HH = `0${date.getHours()}`.slice(-2);
    const mm = `0${date.getMinutes()}`.slice(-2);
    if (file instanceof Blob) {
      ext = 'jpg';
    } else {
      ext = (file as File).name.split('.').pop();
    }

    return `MegatronWeb/${phone ?? 'default'}/${path ?? 'default'}/${YYYY + MM}/${YYYY + MM + DD}_${
      HH + mm
    }_${uuid()}_Web.${ext}`;
  }

  // 直传
  ossUploadFn(file: File, dir: string, phone: string): Promise<PutObjectResult> | undefined {
    const filePath = this.getFilePath(file, dir, phone);
    return OssUploadApi.ossClient?.put(
      filePath,
      file,
      //headers
    );
  }
  //分片上传
  ossMultipartUploadFn(
    file: File | Blob,
    dir: string,
    phone: string,
    progressCallBack: (percent: number) => void,
  ): Promise<MultipartUploadResult> | undefined {
    const filePath = this.getFilePath(file, dir, phone);
    return OssUploadApi.ossClient?.multipartUpload(filePath, file, {
      // 设置并发上传的分片数量。
      parallel: 4,
      // 设置分片大小。默认值为1 MB，最小值为100 KB。 //小于100kb是直传
      partSize: 1024 * 1024,
      progress: (p: number, cpt: any, res: any) => {
        //cpt:取消分片上传时候
        // 获取上传进度。
        // console.log('上传进度', p);
        progressCallBack(p);
      },
    });
  }
}
